﻿using System;
using System.Threading.Tasks;
using FDSimpleModelGenerator.Common;
using FDSimpleModelGenerator.Common.Mvc;
using FDSimpleModelGenerator.Common.Mvc.Filters;
using FDSimpleModelGenerator.Common.Mvc.PageModels;
using FDSimpleModelGenerator.Entities;
using FDSimpleModelGenerator.ImageCode;
using FDSimpleModelGenerator.IServices;
using FDSimpleModelGenerator.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace FDSimpleModelGenerator.Pages
{
    /// <summary>
    /// 注册
    /// </summary>
    public class RegisterModel : LoginBaseModel
    {
        private readonly IWebHostEnvironment _environment;
        private readonly ISysUserService _sysUserService;
        private readonly ICache _cache;
        private static readonly string ImageCodeKey = "ht_nicao2019hepita";

        public RegisterModel(IWebHostEnvironment environment, ISysUserService sysUserService,
            ICache cache)
        {
            _cache = cache;
            _environment = environment;
            _sysUserService = sysUserService;
        }

        public void OnGet()
        {
            //var n = _sysUserService.Get(1);
        }

        public async Task<IActionResult> OnPostAsync(RegisterParamModel model)
        {
            string returnUrl = Request.Query["ReturnUrl"];
            returnUrl = returnUrl.IsNullOrEmpty() ? "/" : returnUrl;
            if (Request.Cookies.TryGetValue(ImageCodeKey, out string imgKey))
            {
                string code = _cache.Get<string>(imgKey);
                if (!code.IsNullOrEmpty() && string.Equals(code, model.Code, StringComparison.OrdinalIgnoreCase))
                {
                    model.UserName = model.UserName.Trim();
                    if (_sysUserService.IsExists(model.UserName))
                    {
                        ModelState.AddModelError("UserName", $"the name of {model.UserName} was exists.");
                    }
                    else
                    {
                        if (model.Password != model.ConfirmPassword)
                        {
                            ModelState.AddModelError("ConfirmPassword", $"the confirm password not match the password.");
                        }
                        var res = _sysUserService.Add(new SysUser
                        {
                            CreateTime = DateTime.Now,
                            IsEnable = true,
                            Password = model.Password.ToEncryptString(),
                            UserName = model.UserName
                        });
                        if (res)
                        {
                            var userId = _sysUserService.GetId(model.UserName);
                            await UserContext.Current.LoginAsync(model.UserName, userId);
                        }
                        else
                        {
                            ModelState.AddModelError("", $"login by the name of {model.UserName} failure.");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", $"image code is invalid.");
                }
            }
            else
            {
                ModelState.AddModelError("", $"image code is invalid.");
            }

            if (ModelState.IsValid)
            {
                return Redirect(returnUrl);
            }

            return Page();
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public IActionResult OnGetImgCode()
        {
            var imgCode = new BasicImageCode(6, 2, 40);
            imgCode.CreateImage();
            //imgCode.Image.Save($"{_environment.WebRootPath}/demo.jpg", ImageFormat.Jpeg);
            var imageKey = Guid.NewGuid().ToString().Replace("-", "");
            Response.Cookies.Append(ImageCodeKey, imageKey);
            _cache.Set(imageKey, imgCode.Code, TimeSpan.FromMinutes(10));
            return File(imgCode.Buffer, "image/jpeg");
        }
    }
}